/**
 * 
 */
package com.objectdraw.server;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;

import com.objectdraw.server.data.ResponseData;

/**
 * This class is responsible for opening up a socket on the host machine and passing any
 * service request to the Object Draw Server
 * @author Harrison
 */
public class CommunicationServer {

	public static void main(String args[]){

		CommunicationServer cs = new CommunicationServer();
		cs.listen(5454);

	}
	
	void listen(int port){
		try {
			ServerSocket listener = new ServerSocket(port);
			System.out.println("Object Draw Server running on port "+port);
			
			while(true){
				Socket client = listener.accept();
			
				//Pass the client on to an Object Draw Handler
				new ObjectDrawHandler(client,this).start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	/**
	 * Broadcast a response to a set of clients
	 * @param response is the message you would like sent to the client
	 * @param to is a socket connections to client
	 */
	public synchronized void broadcast(ResponseData response,Socket to){
		try {
			PrintWriter out = new PrintWriter(new OutputStreamWriter(to.getOutputStream()),true);
			out.println(response.toString());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	/**
	 * Broadcast a response to a set of clients
	 * @param response is the message you would like sent to the client
	 * @param to is a list of socket connections to clients
	 */
	public synchronized void broadcast(ResponseData response,List<Socket> to){
		//TODO: Stuff
	}
}
